package com.darco.darcoapp;

import static DARCOShared.utils.Constants.*;


import com.darco.darcoapp.db.DarcoData;
import com.google.zxing.integration.android.IntentIntegrator;

import eneter.messaging.endpoints.typedmessages.TypedResponseReceivedEventArgs;
import DARCOShared.requests.GetCardFromQRScanRequest;
import DARCOShared.responses.GetCardFromQRScanResponse;
import DARCOShared.responses.ResponseBase;
import DARCOShared.responses.ResponseType;
import DARCOShared.responses.ResponseWrapper;
import android.os.Bundle;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ScanActivity extends MessagingActivity implements OnClickListener {
	private MessagingManager mm;
	private DarcoData d;
	private Bundle extra=null;
	private ContentValues account=null;
	private int scan_actionToDo;	//action to do after the qrscan
	private ContentValues cardInfo;
	private ContentValues uniqueInfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scan);

		d= new DarcoData(this);
		//click listener for all buttons
		View scan4auth_button = findViewById(R.id.scan_scan4auth_button);
		scan4auth_button.setOnClickListener(this);

		View scan4info_button = findViewById(R.id.scan_scan4info_button);
		scan4info_button.setOnClickListener(this);

		extra=getIntent().getExtras();
		if(extra!=null){
			account=((ContentValues) extra.get("account"));
			byte[] image_avatar = account.getAsByteArray(ACCOUNT_AVATAR);
			String account_name = account.getAsString(ACCOUNT_USERNAME);
			TextView account_greatings=(TextView) findViewById(R.id.scan_greatings_textView);

			if(image_avatar!=null){
				//account_greatings.setCompoundDrawables(Drawable.createFromStream(new ByteArrayInputStream(image_avatar), "avatar"), null,null,null);
				Bitmap bmp = BitmapFactory.decodeByteArray(image_avatar,0,image_avatar.length);
				if(bmp!=null){
					((ImageView) findViewById(R.id.scan_avatar_imageView)).setImageBitmap(bmp);
				}
			}
			if(account_name!=null)
				account_greatings.setText("Hi, "+account_name);

		}
		else{
			Toast.makeText(this, "Error: no account data found", Toast.LENGTH_LONG).show();
			//back to main
			//startActivity(new Intent(this,Login_Activity.class));
		}


	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_scan, menu);
		return true;
	}


	@Override
	public void onClick(View arg0) {
		switch(arg0.getId()){
		case R.id.scan_scan4auth_button:
			scan_actionToDo=0;
			break;
		case R.id.scan_scan4info_button:
			//todo
			scan_actionToDo=1;
			break;
		}
		IntentIntegrator integrator = new IntentIntegrator(this);
		integrator.initiateScan();
	}


	@Override
	public void onActivityResult(int requestCode,int resultCode,Intent intent){
		switch(scan_actionToDo){
		case 0:	//scan4auth
			if(resultCode== RESULT_OK){
				String content= intent.getStringExtra("SCAN_RESULT");
				String format= intent.getStringExtra("SCAN_RESULT_FORMAT");
				if(format.compareTo("QR_CODE")==0){
					String[] scanResult = content.split("[\\[,\\]]");
					GetCardFromQRScanRequest req= new GetCardFromQRScanRequest(scanResult[1], scanResult[2], account.getAsString(ACCOUNT_EMAIL));
					onPerformRequest(req);
				}
				else
					Toast.makeText(this, "Format of scan is not QR_CODE", Toast.LENGTH_SHORT).show();

			}
			else{
				if(resultCode==RESULT_CANCELED){
					Toast.makeText(this, "Acquisizione per autenticazione cancellata", Toast.LENGTH_LONG).show();
				}
			}
			break;
		case 1:	//scan4info
			if(resultCode== RESULT_OK){
				String content= intent.getStringExtra("SCAN_RESULT");
				String format= intent.getStringExtra("SCAN_RESULT_FORMAT");
				if(format.compareTo("QR_CODE")==0){
					String[] scanResult = content.split("[\\[,\\]]");

					String sn=scanResult[1];
					String id=scanResult[2];
					//cerco se la carta c'è gia nel db
					uniqueInfo= d.getUniqueCardFromLocalDB(sn, id);
					if(uniqueInfo!=null){
						cardInfo= d.getCardFromLocalDB(sn);
						if(cardInfo!=null){
							//procedo con la visualizzazione delle cardInfo
							Intent visual= new Intent(this, Visualization_Activity.class);
							visual.putExtra("cardInfo", cardInfo);
							visual.putExtra("uniqueInfo", uniqueInfo);
							visual.putExtra("account", account);
							visual.putExtra("ORIGIN_ACTIVITY", "QR_SCAN"); //dichiara l'origine per la visualizzazione
							int reqCode = 2;
							startActivityForResult(visual, reqCode);
						}
						else{
							Toast.makeText(this, "Error: no card info of uniquecard found on db", Toast.LENGTH_LONG).show();
						}
					}
					else{
						showLoadingDialog("Waiting for Card Data");
						GetCardFromQRScanRequest req= new GetCardFromQRScanRequest(scanResult[1], scanResult[2]);
						onPerformRequest(req);
					}
				}
				else
					Toast.makeText(this, "Format of scan is not QR_CODE", Toast.LENGTH_SHORT).show();

			}
			else{
				if(resultCode==RESULT_CANCELED){
					Toast.makeText(this, "Acquisizione per informazione cancellata ", Toast.LENGTH_LONG).show();
				}
			}
			break;

		case 3:
			//ritorno da visualizzazione carta
			break;
		}
	}

	void onPerformRequest(GetCardFromQRScanRequest req){
		//inizializzazione ...
		mm = new MessagingManager();
		mm.ConnectToServer(this); //mi connetto al server e mi iscrivo alle risposte
		mm.SendRequest(req, this); //invia una richiesta di info carta
		//qui sara necessario mostrare un popup di attesa, tipo "caricamento in corso" o roba simile
		//Toast.makeText(getApplicationContext(), "Request sent!", Toast.LENGTH_SHORT).show();
		
	}

	@Override
	void onResponseReceived(Object sender, TypedResponseReceivedEventArgs<ResponseWrapper> e) {
		ResponseBase respbase = e.getResponseMessage().getResponse();
		ResponseType resptype=respbase.getResponseType();
		
		switch(resptype){
		case GetCardFromQRScan:			
			GetCardFromQRScanResponse respqr= (GetCardFromQRScanResponse) respbase;
			if(respqr.err==true){
				hideLoadingDialog();
				Toast.makeText(this, respqr.error , Toast.LENGTH_LONG).show();
			}
			else{
				//richesta è andata a buon fine
				if(respqr.authPerformed){
					//richiesta di autenticazione
					hideLoadingDialog();
					Toast.makeText(this, "authentication success for card: "+respqr.cardName+" to account: "+respqr.owner, Toast.LENGTH_LONG).show();
				}
				else{
					//richiesta di visualizzazione informazioni
					//visualizzazione informazioni della carta
					cardInfo = new ContentValues();
					uniqueInfo = new ContentValues();

					cardInfo.put(CARD_NAME , respqr.cardName );
					cardInfo.put( CARD_SN, respqr.cardSN );
					cardInfo.put( CARD_STATS, respqr.cardStats );
					cardInfo.put( CARD_SPECIAL, respqr.cardSpecial );
					cardInfo.put( CARD_CATEGORY, respqr.categoryID );
					cardInfo.put( CARD_CATEGORY_NAME, respqr.categoryName );
					cardInfo.put( CARD_SUBCATEGORY, respqr.subCategoryID );
					cardInfo.put( CARD_SUBCATEGORY_NAME, respqr.subCategoryName );
					cardInfo.put( CARD_PREVIEW, respqr.cardPreview );
					cardInfo.put( ACCOUNT_KEYPAIR, respqr.ownerPubKey ); //uso questo

					uniqueInfo.put( UNIQUECARD_ACTUALOWNER, respqr.owner );
					uniqueInfo.put( UNIQUECARD_ID, respqr.cardID );
					uniqueInfo.put(UNIQUECARD_SN,respqr.cardSN );
					uniqueInfo.put( UNIQUECARD_AUTENTICATED, respqr.authenticated );
					uniqueInfo.put( UNIQUECARD_FIRSTOWNER, respqr.firstOwner );
					uniqueInfo.put( UNIQUECARD_FIRSTAUTH, respqr.firstAuth );

					//inserimento nel database TODO by thread
					//salvo unique card se e solo se sono io il proprietario
					if(respqr.owner!=null && (account.getAsString(ACCOUNT_EMAIL)).compareTo(respqr.owner)==0){
						d.insertUniqueCard(respqr.cardSN, respqr.cardID, respqr.authenticated, respqr.owner,
								respqr.firstAuth, respqr.firstOwner);
					}
					d.insertCategory(respqr.categoryID, respqr.categoryName, 0);
					d.insertCategory(respqr.categoryID, respqr.categoryName, 0);
					d.insertCard(respqr.cardSN, respqr.cardName, respqr.cardStats, respqr.cardSpecial, respqr.categoryID,
							respqr.subCategoryID, respqr.cardPreview, null);

					Intent visual= new Intent(this, Visualization_Activity.class);
					visual.putExtra("cardInfo", cardInfo);
					visual.putExtra(VISUALIZATION_ORIGIN, VISUALIZATION_FROM_QRSCAN4INFO); //dichiara l'origine per la visualizzazione
					visual.putExtra("uniqueInfo", uniqueInfo);
					visual.putExtra("account", account);
					hideLoadingDialog();
					startActivityForResult(visual, VISUALIZATION_FROM_QRSCAN4INFO);
				}

			}
			break;
		default:
			break;


		}
	}

}
